package com.gzdict.common.ui

import android.animation.ObjectAnimator
import android.app.Dialog
import android.content.Context
import android.graphics.Color
import android.os.Bundle
import android.view.Gravity
import android.view.View
import android.view.animation.LinearInterpolator
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import com.gzdict.common.R
import com.gzdict.common.ext.dp

class NetRequestDialog(val msg: String? = "加载中...", context: Context) : Dialog(context) {

    lateinit var animator: ObjectAnimator

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        window?.setBackgroundDrawableResource(android.R.color.transparent)
        setContentView(createMyView())
        setCancelable(false)
        animator.start()
    }

    private fun createMyView(): View {
        val rootContainer = LinearLayout(context)
        rootContainer.setBackgroundResource(R.drawable.shape_black_5)
        rootContainer.orientation = LinearLayout.VERTICAL
        val img = ImageView(context)
        img.setImageResource(R.drawable.ic_dialog_roadding)

        val params = LinearLayout.LayoutParams(120f.dp(context).toInt(), 120f.dp(context).toInt())
        params.topMargin = 27f.dp(context).toInt()
        params.leftMargin = 40f.dp(context).toInt()
        params.rightMargin = 40f.dp(context).toInt()
        params.bottomMargin = 24f.dp(context).toInt()
        animator = ObjectAnimator.ofFloat(img, "rotation", 0f, 359f)
        animator.duration = 3000
        animator.interpolator = LinearInterpolator()
        animator.repeatCount = -1
        rootContainer.addView(img, params)

        val msgTextView = TextView(context)
        msgTextView.setTextColor(Color.WHITE)
        msgTextView.textSize = 16f
        msgTextView.text = msg
        val msgParam = LinearLayout.LayoutParams(
            LinearLayout.LayoutParams.WRAP_CONTENT,
            LinearLayout.LayoutParams.WRAP_CONTENT
        )
        msgParam.gravity = Gravity.CENTER_HORIZONTAL
        msgParam.bottomMargin = 14f.dp(context).toInt()
        rootContainer.addView(msgTextView, msgParam)
        return rootContainer
    }

    override fun onDetachedFromWindow() {
        super.onDetachedFromWindow()
        animator.cancel()
    }
}